package models

import play.api.Logging

import java.sql.Timestamp
import play.api.db.slick.{DatabaseConfigProvider, HasDatabaseConfigProvider}
import slick.jdbc.JdbcProfile

import java.time.LocalDateTime
import javax.inject.{Inject, Singleton}
import scala.concurrent.duration.Duration
import scala.concurrent.{Await, ExecutionContext, Future}

case class Kanban(id: Int, shop: String, person: String, date: String, persent: Int, user: Int, modify_date: Timestamp = Timestamp.valueOf(LocalDateTime.now()))

@Singleton
class KanbanRepository @Inject()(protected val dbConfigProvider: DatabaseConfigProvider)(implicit executionContext: ExecutionContext)
  extends HasDatabaseConfigProvider[JdbcProfile] with Logging {
  //  private val dbConfig = dbConfigProvider.get[JdbcProfile]

  import profile.api._

  private class KanbanTable(tag: Tag) extends Table[Kanban](tag, "Xiaoshou_Kanban".toUpperCase) {
    def id = column[Int]("id".toUpperCase, O.PrimaryKey)

    def shop = column[String]("shop".toUpperCase)

    def person = column[String]("person".toUpperCase)

    def date = column[String]("date".toUpperCase)

    def persent = column[Int]("persent".toUpperCase)

    def user = column[Int]("user".toUpperCase)

    def modify_date = column[Timestamp]("modify_date".toUpperCase)

    def * = (id, shop, person, date, persent, user, modify_date).<>((Kanban.apply _).tupled, Kanban.unapply)
  }

  private val kb = TableQuery[KanbanTable]

  def list = db.run {
    kb.sortBy(_.persent.desc).map(f => f).result
  }

  def insert(data: Kanban) = db.run {
    (kb returning kb.map(_.id)) += data
  }

  def update(kanban: Kanban) = db.run {
    logger.debug(s"$kanban")
    kb.filter(_.id === kanban.id)
      .map(f => (f.shop, f.person, f.date, f.persent, f.user, f.modify_date))
      .update((kanban.shop, kanban.person, kanban.date, kanban.persent, kanban.user, kanban.modify_date))
//      .map(f=>f).update(kanban)
  }

  def delete(id: Int) = {
    logger.debug(s"$id")
    db.run {
      kb.filter(_.id === id).map(f => f).delete
    }
  }

}
